<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getTableListApi,saveTableApi, delTableListApi,getRoleApi } from '@/api/menu'
import { TableData } from '@/api/menu/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag } from 'element-plus'
import { Icon } from '@/components/Icon'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getTableListApi()
    return {
      list: Array.isArray(res.data) ? res.data : (res.data.items || [])
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
    return !!res
  }
})

const { dataList, loading } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  // {
  //   field: 'index',
  //   label: t('userDemo.index'),
  //   type: 'index'
  // },
  {
    field: 'selection',
    type: 'selection',
    width: 60
  },
  {
    field: 'id',
    label: t('menu.id'),
    align: 'center',
    headerAlign: 'center',
    width: 100,
    slots: {
      default: (data: any) => {
        const id = data.row.id
        return (
          <span 
            style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                padding: 8px;
                margin: -8px;
                align-items: center;
                transition: background-color 0.2s;
              "
            onClick={() => action(data.row, 'edit')}
          >
            {id}
          </span>
        )
      }
    }
  },
  {
    field: 'name',
    label: t('menu.menuName'),
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const name = data.row.name
        return <>{name}</>
      }
    }
  },
  // {
  //   field: 'icon',
  //   label: t('menu.icon'),
  //   slots: {
  //     default: (data: any) => {
  //       const icon = data.row.icon
  //       if (icon) {
  //         return (
  //           <>
  //             <Icon icon={icon} />
  //           </>
  //         )
  //       } else {
  //         return <>-</>
  //       }
  //     }
  //   }
  // },
  // {
  //   field: 'meta.permission',
  //   label: t('menu.permission'),
  //   slots: {
  //     default: (data: any) => {
  //       const permission = data.row.meta.permission
  //       return permission ? <>{permission.join(', ')}</> : null
  //     }
  //   }
  // },
  // {
  //   field: 'component',
  //   label: t('menu.component'),
  //   slots: {
  //     default: (data: any) => {
  //       const component = data.row.component
  //       return <>{component === '#' ? '顶级目录' : component === '##' ? '子目录' : component}</>
  //     }
  //   }
  // },
  {
    field: 'url',
    label: t('menu.path'),
    align: 'center',
    headerAlign: 'center',
  },
  {
    field: 'remarks',
    label: t('menu.remarks'),
    align: 'center',
    headerAlign: 'center',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 2
    }
  },
  {
    field: 'ctime',
    label: t('menu.ctime')
  },
  // {
  //   field: 'action',
  //   label: t('userDemo.action'),
  //   width: 240,
  //   slots: {
  //     default: (data: any) => {
  //       const row = data.row
  //       return (
  //         <>
  //           <BaseButton type="primary" onClick={() => action(row, 'edit')}>
  //             {t('exampleDemo.edit')}
  //           </BaseButton>
  //           <BaseButton type="success" onClick={() => action(row, 'detail')}>
  //             {t('exampleDemo.detail')}
  //           </BaseButton>
  //           <BaseButton type="danger">{t('exampleDemo.del')}</BaseButton>
  //         </>
  //       )
  //     }
  //   }
  // }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('menu.menuName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}
const delLoading = ref(false)
const ids = ref([])
const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    saveLoading.value = true
    await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })

    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>
    <Table
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle"  width="500px" :maxHeight="300">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <!-- <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template> -->
    <template #footer>
      <div v-if="actionType === 'account'">
        <!-- <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton> -->
      </div>
      <div v-else-if="actionType === 'edit'" style="display: flex; justify-content: space-between; align-items: center;">
        <BaseButton :loading="delLoading" type="danger" @click="delData(currentRow)">
          {{ t('exampleDemo.del') }}
        </BaseButton>
        <div>
          <BaseButton
            type="primary"
            :loading="saveLoading"
            @click="save"
            style="margin-right: 8px;"
          >
            {{ t('exampleDemo.save') }}
          </BaseButton>
          <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
        </div>
      </div>
      <div v-else>
        <BaseButton
          type="primary"
          :loading="saveLoading"
          @click="save"
          style="margin-right: 8px;"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </div>
    </template>
  </Dialog>
</template>
